var express = require('express');
var router = express.Router();
var path = require('path');
var filesrc = path.join(__dirname,'..','public','data.json');
var fs = require('fs');
var multer = require('multer');
var upload = multer({
    dest: 'uploads' //上传文件的目录
});

var single = upload.single('myfile');
/* GET home page. */
router.get('/init', function(req, res, next) {
  //res.render('index', { title: 'Express' });
  fs.readFile(filesrc,'utf-8',(err,data)=>{
      if(data){
          res.send(data);
      }else{
          res.json({"默认":[]});
      }
  });
});

router.post('/single',single,function(req,res,next){
    fs.readFile(filesrc,'utf-8',function(err,data){

        if(data){
            var orgdata = JSON.parse(data);
            if(!orgdata[req.body.type]){
                orgdata[req.body.type]= [];
            }
            orgdata[req.body.type].push(req.file);
            data = JSON.stringify(orgdata);

        }else{
            var dataJson = {};
            dataJson[req.body.type] = [req.file];
            data = JSON.stringify(dataJson);
        }
        fs.writeFile(filesrc,data,'utf-8',function(){

            res.send(req.file);
        });
    });
});

router.get('/img/:url',function(req,res,next){
    fs.createReadStream('uploads/'+req.params.url).pipe(res);
});

router.post('/category',function(req,res,next){
    fs.readFile(filesrc,'utf-8',(err,data)=>{
        var dataJson = JSON.parse(data);
        if(dataJson){
            res.send(dataJson[req.body.category]||[]);
        }else{
            res.json({"默认":[]});
        }
    });
});

module.exports = router;
